// formFata转化
export const makeFormData = (obj, formData) => {
  const data = []
  if (obj instanceof File) {
    data.push({ key: '', value: obj })
  } else if (obj instanceof Array) {
    for (let j = 0, len = obj.length; j < len; j++) {
      const arr = makeFormData(obj[j])
      for (let k = 0, l = arr.length; k < l; k++) {
        const key = formData ? j + arr[k].key : '[' + j + ']' + arr[k].key
        data.push({ key: key, value: arr[k].value })
      }
    }
  } else if (typeof obj === 'object') {
    for (const j in obj) {
      if (obj[j] !== null && obj[j] !== undefined && obj[j] !== '') {
        const arr = makeFormData(obj[j])
        for (let k = 0, l = arr.length; k < l; k++) {
          const key = formData ? j + arr[k].key : '[' + j + ']' + arr[k].key
          data.push({ key: key, value: arr[k].value })
        }
      }
    }
  } else {
    data.push({ key: '', value: obj })
  }
  if (formData) {
    // 封装
    for (let i = 0, len = data.length; i < len; i++) {
      formData.append(data[i].key, data[i].value)
    }
  } else {
    return data
  }
}

export function formatNumber (n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 日期格式化
export function formatTimestamp (timestamp, type, CHflag) {
  var date = new Date()
  date.setTime(timestamp)

  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  switch (type) {
    case 'date':
      if (CHflag) {
        return formatNumber(year) + '年' + formatNumber(month) + '月' + formatNumber(day) + '日'
      }
      return formatNumber(year) + '-' + formatNumber(month) + '-' + formatNumber(day)
    case 'time':
      return formatNumber(hour) + ':' + formatNumber(minute)
    case 'monthDate':
      if (CHflag) {
        return month + '月' + day + '日'
      }
      return formatNumber(month) + '-' + formatNumber(day)
    case 'yearMonth':
      if (CHflag) {
        return formatNumber(year) + '年' + month + '月'
      }
      return formatNumber(year) + '-' + formatNumber(month)
    case 'dateTime':
      if (CHflag) {
        return (
          formatNumber(year) +
          '年' +
          formatNumber(month) +
          '月' +
          formatNumber(day) +
          '日' +
          ' ' +
          formatNumber(hour) +
          ':' +
          formatNumber(minute) +
          formatNumber(second)
        )
      }
      break
    default:
      return (
        formatNumber(year) +
        '-' +
        formatNumber(month) +
        '-' +
        formatNumber(day) +
        ' ' +
        formatNumber(hour) +
        ':' +
        formatNumber(minute) +
        ':' +
        formatNumber(second)
      )
  }
}

// 转为百分号，保留小数点
export function toPercent (num, total) {
  return Math.round((parseFloat(num) / parseFloat(total)) * 10000) / 100.0 + '%' // 小数点后两位百分比
}

// 金额格式化
export function toThousands (num) {
  let result = ''
  let counter = 0
  const numStr = (num || 0).toString()
  const numArr = numStr.split('.')
  num = numArr[0]
  for (var i = numArr[0].length - 1; i >= 0; i--) {
    counter++
    result = numArr[0].charAt(i) + result
    if (!(counter % 3) && i !== 0) {
      result = ',' + result
    }
  }
  return result + (numArr[1] ? '.' + numArr[1].substring(0, 2) : '.00')
}

// // 当前时间之后
// export function afterNow(current){
//   const moment = require('moment')
//   return current < moment().startOf('day')
// }

// // 当前时间之前
// export function beforeNow(current){
//   const moment = require('moment')
//   return current > moment().endOf('day')
// }

// 文件流导出
export function exportBlob (blob, filename, callback) {
  const blobUrl = window.URL.createObjectURL(blob)
  const aElement = document.createElement('a')
  document.body.appendChild(aElement)
  aElement.style.display = 'none'
  aElement.href = blobUrl
  aElement.download = filename
  aElement.click()
  document.body.removeChild(aElement)
  if (callback) callback()
}

export function download (filename, text) {
  const pom = document.createElement('a')
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text))
  pom.setAttribute('download', filename)
  if (document.createEvent) {
    const event = document.createEvent('MouseEvents')
    event.initEvent('click', true, true)
    pom.dispatchEvent(event)
  } else {
    pom.click()
  }
}

/**
 * @description: 平铺对象列表树
 * @param : tree: 原始树列表， key: children字段, list: 装载平铺列表
 * @return {type}
 */
export function flatTree (tree, key = 'children', list = []) {
  tree.map(item => {
    if (item[key]) {
      if (item[key].length > 0) {
        flatTree(item[key], key, list)
      } else {
        delete item[key]
        list.push(item)
      }
    } else {
      list.push(item)
    }
  })
}

// 倒推数： 联级地址获取
export function backToTree (initlist, code, callback) {
  const mapList = (list, parantCode = '') => {
    const matchItem = list.find(item => {
      return item.value === code
    })

    let codeStr = parantCode

    if (matchItem) {
      codeStr += '/' + matchItem.value
      if (callback) callback(codeStr)
      return codeStr
    }

    list.map(item => {
      if (item.children) {
        mapList(item.children, codeStr + '/' + item.value)
      }
    })
  }

  mapList(initlist, '')
}

export function treeReplaceKeys (list, keysObj) {
  list.forEach(item => {
    for (const key in keysObj) {
      item[keysObj[key]] = item[key].toString()
    }
    if (item.children && item.children.length > 0) {
      treeReplaceKeys(item.children, keysObj)
    } else {
      delete item.children
    }
  })

  return list
}

export function treeDisabled (list, key, pattern) {
  list.forEach(item => {
    if (pattern.test(item[key])) {
      item.disabled = true
    } else {
      item.disabled = false
    }
    if (item.children && item.children.length > 0) {
      treeDisabled(item.children, key, pattern)
    }
  })
  return list
}

export function getTreeNode (list, key, childrenKey, val) {
  console.log(list)
  return new Promise(resolve => {
    const mapList = list => {
      list.map(x => {
        if (x[key] === val) {
          resolve(x)
        } else {
          if (x[childrenKey]) {
            mapList(x[childrenKey])
          }
        }
      })
    }
    mapList(list)
  })
}

/**
 * 数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
export const listToTree = (list, tree, pid, key, pidKey = 'pid') => {
  list.forEach(item => {
    // 判断是否为父级菜单
    if (item[pidKey] === pid) {
      const child = {
        ...item,
        key: item[key].toString(),
        children: []
      }
      // 迭代 list， 找到当前菜单相符合的所有子菜单
      listToTree(list, child.children, item[key], key, pidKey)
      // 删掉不存在 children 值的属性
      if (child.children.length <= 0) {
        delete child.children
      }
      // 加入到树中
      tree.push(child)
    }
  })
}

// 用JS获取地址栏参数的方法（超级简单）
export function getQueryString (name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  var r = window.location.search.substr(1).match(reg) // search,查询？后面的参数，并匹配正则
  if (r != null) {
    return decodeURIComponent(r[2])
  }
  return null
}

export function setUrlParams (field = 'pager', params) {
  const urlParams = new URL(window.location.href)
  if (typeof params === 'object') {
    urlParams.searchParams.set(field, JSON.stringify(params))
  } else {
    urlParams.searchParams.set(field, params)
  }
  window.history.replaceState(null, field, urlParams.href)
}

export function deleteUrlParams (field) {
  const urlParams = new URL(window.location.href)
  if (field && urlParams.searchParams.has(field)) {
    try {
      urlParams.searchParams.delete(field)
    } catch (err) {
      console.log(err)
    }
  }
  window.history.replaceState(null, field, urlParams.href)
}

// 获取当前浏览器类型
export function myBrowser () {
  var userAgent = navigator.userAgent // 取得浏览器的userAgent字符串
  var isOpera = userAgent.indexOf('Opera') > -1
  if (isOpera) {
    // 判断是否Opera浏览器
    return 'Opera'
  }
  if (userAgent.indexOf('Firefox') > -1) {
    // 判断是否Firefox浏览器
    return 'FF'
  }
  if (userAgent.indexOf('Chrome') > -1) {
    return 'Chrome'
  }
  if (userAgent.indexOf('Safari') > -1) {
    // 判断是否Safari浏览器
    return 'Safari'
  }
  if (userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 && !isOpera) {
    // 判断是否IE浏览器
    return 'IE'
  }
}
